import { indexManagementApi } from "@/api/esArticle";
import esServerIndexFieldStore from "@/stores/esServerIndexField";
import { formatTime } from "@/utils/common";
import mainStore from "@/stores/main";
import { Tag, type TableColumnsType, Space, Popconfirm, message, Button, TypographyText } from "ant-design-vue";
import { useAdminShow } from "./useCommon";
const $store = esServerIndexFieldStore();
const esServerIndexMap = toRef($store, "esServerIndexMap");
// 索引管理

/**
 * 判断一个索引是否存在当前服务器
 * @param esHost es服务器
 * @param index  索引
 * @returns {boolean}
 * @example isExistIndex("http://192.168.1.90:9200", "keywords")
 */
export function isExistIndex(esHost: string, index: string): boolean {
    return esServerIndexMap.value[esHost].some((item) => item.value === index);
}

export function useColumns(
    userOptions: Ref<SelectOption>,
    websiteGroupOptions: Ref<SelectOption>,
    websiteTypeOptions: Ref<SelectOption>,
    artWycOptions: Ref<SelectOption>,
    indexTypeOptions: SelectOption
) {
    // indexModal显示和隐藏
    const indexModalVisible = ref(false);
    // 1 添加 2 导入 3 修改
    const handleType = ref<1 | 2 | 3>(1);
    // 当前操作的索引信息
    const dataInfo = ref<Partial<IndexManagementItem>>({});
    // 是否重新加载
    const isReload = ref(false);
    const customRenderFunc: TableColumnsType[0]["customRender"] = (row) => {
        const map = {
            website_group_id: websiteGroupOptions.value,
            index_type: indexTypeOptions,
            trade_type_id: websiteTypeOptions.value,
            wyc_type: artWycOptions.value,
            create_id: userOptions.value
        };
        // @ts-ignore
        if (!map[row.column.dataIndex]) {
            return;
        }
        // @ts-ignore
        const value = (map[row.column.dataIndex].find((item) => item.value == row.value) || { label: "暂无" }).label;
        return h("div", [value]);
    };
    const columns: TableColumnsType = [
        {
            title: "索引名",
            width: 120,
            dataIndex: "index_name",
            key: "index_name",
            fixed: "left",
            align: "center",
            customRender(row) {
                return h(
                    Button,
                    {
                        type: "link",
                        onClick() {
                            const pathname = window.location.pathname;
                            window.open(
                                `${pathname}#/esarticle/es-action?host=${row.record.es_host}&index=${row.record.index_name}`
                            );
                        }
                    },
                    {
                        default: () => row.record.index_name
                    }
                );
            }
        },
        {
            title: "ES_HOST",
            width: 200,
            dataIndex: "es_host",
            key: "es_host",
            align: "center",
            fixed: "left"
        },
        {
            title: "索引类型",
            width: 80,
            dataIndex: "index_type",
            key: "index_type",
            align: "center",
            customRender: customRenderFunc
        },
        {
            title: "网站组",
            width: 60,
            dataIndex: "website_group_id",
            key: "website_group_id",
            align: "center",
            customRender: customRenderFunc
        },
        {
            title: "行业类型",
            dataIndex: "trade_type_id",
            key: "trade_type_id",
            align: "center",
            width: 100,
            customRender: customRenderFunc
        },
        {
            title: "创建人",
            dataIndex: "create_id",
            key: "create_id",
            width: 80,
            align: "center",
            customRender: customRenderFunc
        },
        {
            title: "伪原创",
            dataIndex: "wyc_type",
            key: "wyc_type",
            width: 100,
            align: "center",
            customRender: customRenderFunc
        },
        {
            title: "公共索引",
            dataIndex: "is_common",
            key: "is_common",
            width: 80,
            align: "center",
            customRender: (row) =>
                h(Tag, { color: row.value === 1 ? "success" : "processing" }, { default: () => (row.value === 1 ? "是" : "否") })
        },
        {
            title: "导入索引",
            dataIndex: "is_outside",
            key: "is_outside",
            width: 80,
            align: "center",
            customRender: (row) =>
                h(Tag, { color: row.value === 1 ? "success" : "processing" }, { default: () => (row.value === 1 ? "是" : "否") })
        },
        {
            title: "描述",
            width: 120,
            dataIndex: "index_description",
            key: "index_description",
            align: "center",
            customRender: (row) => {
                return h(TypographyText, { ellipsis: true }, { default: () => row.value });
            }
        },
        {
            title: "创建时间",
            width: 140,
            dataIndex: "create_time",
            key: "create_time",
            align: "center",
            customRender: (row) => {
                const date = new Date(formatTime(row.value));
                date.setHours(date.getHours() - 8);
                return formatTime(date);
            }
        },
        {
            title: "操作",
            width: 140,
            align: "center",
            customRender(row) {
                const style = { paddingLeft: "5px", paddingRight: "5px" };
                const showBtn = h(Button, { type: "link", style }, { default: () => "查看" });
                const updateBtn = h(
                    Button,
                    {
                        type: "text",
                        onClick() {
                            indexModalVisible.value = true;
                            handleType.value = 3;
                            dataInfo.value = row.record;
                        },
                        style
                    },
                    { default: () => "修改" }
                );
                const deleteBtn = h(
                    Popconfirm,
                    {
                        okText: "确定",
                        cancelText: "取消",
                        title: "确定删除索引吗?",
                        onConfirm: () => {
                            indexManagementApi(
                                {
                                    id: row.record.id,
                                    index: row.record.index_name,
                                    es_host: row.record.es_host
                                },
                                "delete"
                            ).then((res) => {
                                if (res.data.code === 200) {
                                    message.success("操作成功!");
                                    isReload.value = true;
                                } else {
                                    message.error("服务器错误!");
                                }
                            });
                        }
                    },
                    { default: () => h(Button, { type: "link", danger: true, style }, { default: () => "删除" }) }
                );
                const children = [showBtn];
                const $store = mainStore();
                if (useAdminShow()) {
                    children.push(updateBtn);
                    children.push(deleteBtn);
                } else if (row.record.uid === $store.userInfo.id) {
                    children.push(updateBtn);
                }
                return h(Space, { size: 4 }, { default: () => children });
            }
        }
    ];

    return {
        columns,
        isReload,
        indexModalVisible,
        dataInfo,
        handleType
    };
}
